package com.nulldev.util.web.YouTubeExtractor.playlist;

import java.util.List;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Arrays.arrays.FastLists;
import com.nulldev.util.manage.NonStandard;

public class Playlist {

	public static class PlaylistEntry {
		private final String title;
		private final String thumbnail;
		private final String username;
		private final String link;
		private final int index;

		public PlaylistEntry(final String title, final String thumb, final String username, final String link, final int index) {
			this.title = title;
			this.thumbnail = thumb;
			this.username = username;
			this.link = link;
			this.index = index;
		}

		public String getTitle() {
			return this.title;
		}

		public String getThumbnail() {
			return this.thumbnail;
		}

		public String getUsername() {
			return this.username;
		}

		public String getLink() {
			return this.link;
		}

		public int getIndex() {
			return this.index;
		}
	}

	private final List<PlaylistEntry> entries = FastLists.list(32);
	private final String playlistName;

	private PlaylistEntry current;
	private PlaylistEntry next;

	private final int index;

	public Playlist(final String name, final int currentIndex) {
		if (currentIndex < -1)
			throw new IllegalArgumentException("Invalid index: " + currentIndex);
		this.playlistName = Variables.requireNonNullObject(name, "name");
		this.index = currentIndex;
	}

	public boolean hasIndex() {
		return this.index > -1;
	}

	public int getIndex() {
		return this.index + 1; // TODO: Check if correcting from starts-from-zero is a good idea.
	}

	public boolean addEntry(final PlaylistEntry pe) {
		return this.entries.add(pe);
	}

	public String getName() {
		return this.playlistName;
	}

	public List<PlaylistEntry> get() {
		return this.entries;
	}

	public PlaylistEntry current() {
		if (this.next == null) {
			this.next = this.entries.get(0);
		}
		return this.current;
	}

	public void makeCurrent(final PlaylistEntry pe) {
		this.current = pe;
	}

	public void makeNext(final PlaylistEntry pe) {
		this.next = pe;
	}

	public PlaylistEntry next() {
		if (this.entries.size() < 2) {
			return null;
		}
		if (this.next == null) {
			if (this.index + 1 >= this.entries.size()) {
				return (this.next = this.entries.get(0));
			} else {
				return (this.next = this.entries.get(this.index + 1));
			}
		}
		return this.next;
	}

	public PlaylistEntry at(final int index) {
		return this.entries.get(index);
	}

	@NonStandard
	public void clear() {
		this.current = null;
		this.next = null;
		this.entries.clear();
	}

	public int length() {
		return this.entries.size();
	}
}
